package com.xm.servlet.background.commodity;

import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 上传商品图片
 * @author 康文程
 * @date 2024-1-16
 */
@WebServlet("/background/add/commodity/image")
@MultipartConfig
public class AddCommodityImageServlet extends HttpServlet {
    /**
     * 图片保存路径
     */
    private String savePath;

    @Override
    public void init() throws ServletException {
        super.init();
        // 从配置文件中读取图片保存路径
        Properties properties = new Properties();
        InputStream inputStream = getClass().getResourceAsStream("/config.properties");
        try {
            properties.load(inputStream);
            savePath = properties.getProperty("imageSavePath", "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        // 获取商品图片
        Part commodityImagePart = req.getPart("commodityImage");
        // 生成新的文件名，避免文件名冲突 System.currentTimeMillis()毫秒数
        String fileName = System.currentTimeMillis() + "_" + commodityImagePart.getSubmittedFileName();
        // 将商品图片保存到指定路径
        commodityImagePart.write(savePath + fileName);
        // 返回响应信息
        resp.getWriter().print(fileName);
    }
}
